import React, { Component, Fragment } from "react";
// antd
import { Table, Button, Col, Pagination, Form, Input, Space, notification, Typography, Progress, Spin, Modal, Radio, message, Tag, Card, Row, Tooltip, Divider, Select } from "antd";
// http
import http from '../../../utils/request';
import { CopyOutlined, CheckOutlined, SyncOutlined } from '@ant-design/icons';
import {CopyToClipboard} from 'react-copy-to-clipboard';
import Action from "@c/buttonAction/Index";


const { Text } = Typography;
const { Option } = Select;


class Offline extends Component {
    constructor(props){
        super(props);
        this.state = {
            // 表格分页
            total: '',
            page: 1,
            page_number: 10,
            dataSource: [],
            columns: [
                {title: "实例ID/名称", dataIndex: "instance_id", key: "instance_id", width: "270px",
                    render: (text, rowData) => {
                        return(
                            <Space direction="vertical">
                                <CopyToClipboard text={rowData.instance_id} 
                                    onCopy={() => 
                                        this.setState({copied: true},
                                        notification.open({
                                            message: '已复制到剪贴板',
                                            icon: <CheckOutlined style={{ color: 'green' }} />,
                                            duration: 2,
                                            placement: 'top',
                                        })
                                    )}
                                >
                                    <span><span style={{marginRight: "5px"}}><CopyOutlined /></span><span style={{color: "#6587FF"}}>{rowData.instance_id}</span></span>
                                </CopyToClipboard>
                                 
                                <Text >{rowData.instance_name}</Text>
                            </Space>
                        )
                    }
                },
                {title: "任务ID", dataIndex: "task_id", key: "task_id"},
                {title: "进度", dataIndex: "percent", key: "percent",
                    render: (text, rowData) => {return (<Progress size="small" percent={rowData.percent} steps={5} />)}
                },
                {title: "任务状态", dataIndex: "status", key: "status",
                    render: (text, rowData) => {
                        var status_text = null
                        if (rowData.status === 'success') {
                            status_text = <Tag color="green">已完成</Tag>
                        } else if (rowData.status === 'failed') {
                            status_text = <Tag color="red">已失败</Tag>
                        } else if (rowData.status === 'running') {
                            status_text = <Spin size="small"/>
                        } else if (rowData.status === 'pause') {
                            status_text = <Tag color="blue">暂停中</Tag>
                        } else if (rowData.status === 'exit') {
                            status_text = <Tag color="warning">已退出</Tag>
                        }
                        return(<div>{status_text}</div>)
                    }
                },
                {title: "标签", dataIndex: "label", key: "label"},
                {title: "模式", dataIndex: "mode", key: "mode"},
                {title: "用户ID", dataIndex: "user_id", key: "user_id"},
                {title: "详情", dataIndex: "message", key: "message"},
                {title: "时间", dataIndex: "created", key: "created"},
                {title: "操作", dataIndex: "operation", key: "operation", fixed: 'right',
                    render: (text, rowData) => {
                        var task_status_text = <div><Action.Button onClick={() => this.onChangeTaskStatusBtn(rowData)}>任务状态</Action.Button></div>
                        if (rowData.status === "success" || rowData.status === "failed" || rowData.status === "exit") {
                            task_status_text = null
                        }
                        return (
                            <div>
                                {task_status_text}
                                <Action.Button onClick={() => this.onChangeTaskDetailBtn(rowData.task_id)}>任务详情</Action.Button>
                            </div>
                            
                        )
                    }
                }
            ],

            loading: false,
            loading_task_status: false,
            loading_task_detail: false,
            loading_task_detail_text: null,

            search_user_id: '',
            search_instance_id: '',
            search_task_id: '',
            search_mode: null, 

            visible_task_status: null,
            visible_task_detail: null,

            task_node_info: [],
            task_id: null,
            task_interval_id: null,
        }

        this.formRefTaskStatusLabel = React.createRef();

    }

    componentDidMount() {
        this.loadData(this.props.kubernetes_id)
    }

    // 父组件中改变了props传值时触发的函数
    componentWillReceiveProps(nextProps) {
        if (this.props.kubernetes_id !== nextProps.kubernetes_id ) {
            this.loadData(nextProps.kubernetes_id)
        }
    }

    loadData = (kubernetes_id) => {
        this.setState({
            loading: true
        })
        const requestData = {
            'page': this.state.page,
            'limit': this.state.page_number,
            'user_id__contains': this.state.search_user_id,
            'instance_id__contains': this.state.search_instance_id,
            'task_id__contains': this.state.search_task_id,
            'mode': this.state.search_mode
        }

        // 获取分组列表
        http.get('/cloud/kubernetes_offline', {params: requestData}).then(response=>{
            this.setState({
                dataSource: response.data.data.items,
                total: response.data.data.pages.total,
                loading: false
            })
        }).catch()
    }

    /** 切换每页数量 */
    onChangeSizePage = (page, page_number) => {
        this.setState({
            page: page,
            page_number: page_number,
        }, () => {
            this.loadData()
        })
    }

    /** 云平台搜索 */
    onFinishSearch = (data) => {
        this.setState({
            page: 1,
            search_user_id: data.user_id ? data.user_id : null,
            search_instance_id: data.instance_id ? data.instance_id: null,
            search_task_id: data.task_id ? data.task_id : null,
            search_mode: data.mode ? data.mode : null
        })
        this.loadData()
    }

    // 修改任务状态按钮
    onChangeTaskStatusBtn = (data) => {
        http.get('/cloud/kubernetes_offline', {'page': 1,'limit': 1}).then(response=>{
            this.setState({visible_task_status: true})
            this.formRefTaskStatusLabel.current.setFieldsValue({task_id: data.task_id, status: data.status, 'cluster_name': data.instance_name})
        }).catch()
    }

    // 修改任务状态取消
    onFinishTaskStatusCancel = () => {
        http.get('/cloud/kubernetes_offline', {'page': 1,'limit': 1}).then(response=>{
            this.formRefTaskStatusLabel.current.resetFields()
            this.setState({visible_task_status: false})
        }).catch()
    }

    // 修改任务状态提交
    onFinishTaskStatus = (data) => {
        this.setState({loading_task_status: true})
        const requestData = {'status': data.status}
        http.patch('/cloud/kubernetes_offline/' + data.task_id, requestData).then(response=>{
            this.setState({visible_task_status: false, loading_task_status: false})
            message.success(response.data.msg)
            this.formRefTaskStatusLabel.current.resetFields()
        }).catch()
        this.loadData(this.props.kubernetes_id)
    }

    // 任务详情取消
    onFinishTaskDetailCancel = () => {
        clearInterval(this.state.task_interval_id);
        this.setState({ task_interval_id: null, visible_task_detail: false, task_node_info: []});
        this.loadData(this.props.kubernetes_id)
    }

    // 查看任务详情按钮
    onChangeTaskDetailBtn = (task_id) => {
        this.setState({visible_task_detail: true, loading_task_detail: true, loading_task_detail_text: '运行中'})

        const task_interval_id = setInterval(() => {
            http.get('/cloud/kubernetes_offline/' + task_id)
            .then(response => {
                const task_status = response.data.data.status
                if (task_status === 'success' || task_status === 'exit') {
                    clearInterval(this.state.task_interval_id);
                    this.setState({ task_interval_id: null, loading_task_detail: false, loading_task_detail_text: '已完成'})
                }
                this.setState({task_node_info: response.data.data.node_info});
            })
        }, 3000); // 每隔3秒执行一次

        this.setState({ task_interval_id });
    }

    render(){
        const { loading, loading_task_status, loading_task_detail, task_node_info, loading_task_detail_text,
            dataSource, columns, page, total, visible_task_status, visible_task_detail } = this.state
        const rowSelection = {
            onChange: this.onCheckbox
        }
        var myStyle = {margin: '20px'}
        var myStyle1 = {margin: '10px', float: 'right'}

        return (
            <Fragment>
                <Form layout="inline" onFinish={this.onFinishSearch}>
                    <Form.Item label="实例ID" name="instance_id" size="small">
                        <Input placeholder="请输入集群实例ID"  />
                    </Form.Item>

                    <Form.Item label="用户ID" name="user_id" size="small">
                        <Input placeholder="yuehua.wl"  />
                    </Form.Item>

                    <Form.Item label="任务ID" name="task_id" size="small">
                        <Input placeholder="bhdpic" />
                    </Form.Item>

                    <Form.Item label="下线模式" name="mode" size="small">
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 180 }}
                            placeholder="选择下线模式"
                        >
                            <Option key="节点">节点 (节点标签)</Option>
                            <Option key="项目">项目 (项目标签)</Option>
                        </Select>                      
                    </Form.Item>

                    <Form.Item shouldUpdate={true}>
                        <Button type="primary" htmlType="submit">搜索</Button>
                    </Form.Item>
                </Form>
                
                <div style={myStyle1}></div>
                <Table
                    pagination={false} 
                    rowSelection={rowSelection} 
                    rowKey="id" 
                    columns={columns} 
                    dataSource={dataSource}
                    loading={loading}
                    scroll={{ y: 600, x: 1500 }}
                >
                </Table>

                <div style={myStyle}>
                    <Col span={16}>
                        <Pagination
                            onChange={this.onChangeSizePage}
                            current={page}
                            total={total}
                            showSizeChanger
                            showQuickJumper
                            showTotal={total => `Total ${total} items`}
                        />
                    </Col>
                </div>

                <Modal
                    title="任务状态"
                    visible={visible_task_status}
                    onCancel={this.onFinishTaskStatusCancel}
                    okText="确认"
                    cancelText="取消"
                    footer={null}
                >
                    <Form
                        onFinish={this.onFinishTaskStatus}
                        ref={this.formRefTaskStatusLabel}
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 14 }}
                    >

                        <Form.Item label="任务ID" name="task_id" rules={[{ required: true}]}>
                            <Input disabled></Input>
                        </Form.Item>

                        <Form.Item label="集群名称" name="cluster_name" rules={[{ required: true}]}>
                            <Input disabled></Input>
                        </Form.Item>

                        <Form.Item label="任务状态" name="status" rules={[{ required: true}]}>
                            <Radio.Group>
                                <Radio value='running'>运行</Radio>
                                <Radio value='pause'>暂停</Radio>
                                <Radio value='exit'>退出</Radio>
                            </Radio.Group>
                        </Form.Item>

                        <Form.Item>
                            <Button loading={loading_task_status} htmlType="submit" type="primary">确定</Button>
                        </Form.Item>                                                               
                    </Form>           
                </Modal>

                <Modal
                    title="任务详情"
                    visible={visible_task_detail}
                    onCancel={this.onFinishTaskDetailCancel}
                    okText="确认"
                    cancelText="取消"
                    footer={null}
                    width={1000}
                >
                    <div style={{marginBottom: "10px"}}>
                        <Button loading={loading_task_detail} onClick={() => this.onChangeTaskDetailBtn(this.state.task_id)}>{loading_task_detail_text}</Button>
                    </div>
                    {
                        task_node_info.map((node_item, index) => (
                            <div key={index}>
                                <Card>
                                    <div style={{marginBottom: "10px", fontSize: "16px"}}>
                                        <Row>
                                            <Col span={3}>
                                                <Progress size="small" percent={node_item.percent} steps={10} />
                                            </Col>
                                            <Col span={19}>
                                                <Tooltip title={node_item.message}>
                                                    <div style={{display: "flex", alignItems: "center"}}>
                                                        <img src="https://yunwei-public.oss-cn-zhangjiakou.aliyuncs.com/ops/common/server-b.png" alt="logo" style={{ height: '20px', display: "inline"}}/> 
                                                        <span style={{paddingTop: "1px", marginLeft: "10px"}}>{node_item.node_name} [{node_item.name}]</span>
                                                    </div>
                                                </Tooltip>
                                            </Col>
                                            <Col span={2}>
                                                {node_item.status === 0 && (
                                                    <span style={{color: "green", fontSize: "12px"}}>OK</span>
                                                )}
                                                {node_item.status === 2 && (
                                                    <span style={{color: "red", fontSize: "12px"}}>Error</span>
                                                )}
                                                {node_item.status === 3 && (
                                                    <SyncOutlined spin />
                                                )}
                                                {node_item.status === 4 && (
                                                    <span style={{fontSize: "12px"}}>Waiting...</span>
                                                )}
                                            </Col>
                                        </Row>
                                    </div>
                                    {node_item.pod.map((pod_item, pod_index) =>(
                                        <div key={pod_index}>
                                            <Row>
                                                <Col span={3}>
                                                    <div>
                                                        {pod_item.status === 3 && (
                                                        <SyncOutlined spin />
                                                        )}
                                                        {pod_item.status === 0 && (
                                                            <Tooltip title={pod_item.message}>
                                                                <img src="https://yunwei-public.oss-cn-zhangjiakou.aliyuncs.com/ops/common/success1.png" alt="logo" style={{ height: '16px'}}/>
                                                            </Tooltip>
                                                        )}
                                                        {pod_item.status === 2 && (
                                                            <Tooltip title={pod_item.message}>
                                                                <img src="https://yunwei-public.oss-cn-zhangjiakou.aliyuncs.com/ops/common/failed1.png" alt="logo" style={{ height: '16px'}}/>
                                                            </Tooltip>
                                                        )}
                                                        {pod_item.status === 1 && (
                                                            <Tooltip title={pod_item.message}>
                                                                <img src="https://yunwei-public.oss-cn-zhangjiakou.aliyuncs.com/ops/common/failed1.png" alt="logo" style={{ height: '16px'}}/>
                                                            </Tooltip>
                                                        )}
                                                    </div>
                                                </Col>
                                                <Col span={13}>
                                                    <Tooltip title={pod_item.pod_name}>
                                                        <div style={{display: "flex", alignItems: "center"}}>
                                                            <img src="https://yunwei-public.oss-cn-zhangjiakou.aliyuncs.com/ops/common/docker.png" alt="logo" style={{ height: '16px', display: "inline"}}/> 
                                                            <span style={{paddingTop: "3px", marginLeft: "10px"}}>{pod_item.project_name}</span>
                                                        </div>
                                                    </Tooltip>
                                                </Col>

                                                <Col span={8}>
                                                    {pod_item.pod_selectors.map((label, label_index) => (
                                                        <span key={label_index}>
                                                            <Tag color="#80bfff">
                                                                {label}
                                                            </Tag>
                                                        </span>
                                                    ))}
                                                </Col>
                                            </Row>
                                        </div>
                                    ))}
                                </Card>
                                <Divider />

                            </div>
                        ))
                    }
                </Modal>
            </Fragment>
        )
    }
}
export default Offline;